package com.example.navigationview

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.MarginPageTransformer
import com.google.android.material.navigation.NavigationView
import com.google.android.material.tabs.TabLayout

class MainActivity : AppCompatActivity() {

    private lateinit var drawerLayout: DrawerLayout
    private lateinit var viewPager: ViewPager
    private lateinit var tabLayout: TabLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        viewPager = findViewById(R.id.viewpager)
        drawerLayout = findViewById(R.id.drawerLayout)
        tabLayout = findViewById(R.id.tabLayout)
        val navigationView = findViewById<NavigationView>(R.id.nv_main_navigation)
        navigationView.setNavigationItemSelectedListener {
            val title = it.title
            Toast.makeText(this, title, Toast.LENGTH_SHORT).show()
            drawerLayout.closeDrawers()
            return@setNavigationItemSelectedListener true
        }
        initViewPager()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_overaction, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId) {
            android.R.id.home -> drawerLayout.openDrawer(GravityCompat.START)
        }
        return super.onOptionsItemSelected(item)
    }

    private fun initViewPager() {
        val titles = mutableListOf<String>()
        titles.add("精选")
        titles.add("体育")
        titles.add("巴萨")
        titles.add("购物")
        titles.add("明星")
        titles.add("视频")
        titles.add("健康")
        titles.add("励志")
        titles.add("图文")
        titles.add("本地")
        titles.add("动漫")
        titles.add("搞笑")
        titles.add("精选")

        for (title in titles) {
            tabLayout.addTab(tabLayout.newTab().setText(title))
        }
        val fragments = mutableListOf<Fragment>()
        for (i in 0 until titles.size) {
            fragments.add(ListFragment())
        }
        val fragmentAdapter = FragmentAdapter(supportFragmentManager, fragments, titles)
        //给ViewPager设置适配器
        viewPager.adapter = fragmentAdapter
        //将TabLayout和ViewPager关联起来。
        tabLayout.setupWithViewPager(viewPager)
    }
}
